import java.io.*;
import java.util.Scanner;

public class demo9 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要搜索的根目录：");
        File Dir = new File(sc.nextLine());

        if(!Dir.isDirectory()){
            System.out.println("输入的目录不存在");
            return;
        }

        System.out.println("请输入要查找的词汇：");
        String word = sc.nextLine();

        scanDir(Dir,word);
    }

    private static void scanDir(File dir, String word) {
        File[] files = dir.listFiles();
        if(files == null){
            return ;
        }

        //遍历元素
        for (File f : files) {
            if(f.isFile()){
                String cont = readFile(f);
                if(cont.contains(word)){
                    System.out.println(f.getAbsolutePath() + "查找成功");
                }
            } else if (f.isDirectory()){
                scanDir(f,word);
            } else {
                continue;
            }
        }
    }

    private static String readFile(File f) {
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader = new FileReader(f)) {
            while(true){
                int c = reader.read();
                if(c == -1){
                    break;
                }
                stringBuilder.append((char)c);
            }
        }  catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}
